package com.example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.TwitterException;
import winterwell.jtwitter.Twitter.Status;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;

public class ListTimeline extends ListActivity implements
		AdapterView.OnItemSelectedListener {
	static final String TAG = "Timeline";
	private Spinner m_myDynamicSpinner;
	private ArrayAdapter<CharSequence> m_adapterForSpinner;

	private Twitter twitter;
	private Map<String, String> lists;
	private StatusAdapter m_adapter;
	private ArrayList<Status> m_status = null;
	private ProgressDialog m_ProgressDialog = null;
	@SuppressWarnings("unused")
	private ListView listTimeline;
	private List<Status> timeline = null;
	private Handler listMessageHandler;
	private Handler listStatusMessageHandler;
	private SharedPreferences prefs;
	private boolean requery = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_timeline);

		// Find the Spinner Control by id
		m_myDynamicSpinner = (Spinner) findViewById(R.id.spinner);
		m_myDynamicSpinner.setOnItemSelectedListener(this);

		// Create the adapter for the spinner
		m_adapterForSpinner = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinner
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		m_myDynamicSpinner.setAdapter(m_adapterForSpinner);

		// Set up the listview containers
		m_status = new ArrayList<Status>();
		m_adapter = new StatusAdapter(this, R.layout.row, m_status);
		setListAdapter(m_adapter);

		// Set up the listeners for the threads that may take time to execute
		listMessageHandler = new ListMessageHandler(getApplicationContext(),
				m_adapterForSpinner);
		listStatusMessageHandler = new ListStatusMessageHandler(m_adapter);

		// Find list view by id
		listTimeline = (ListView) findViewById(R.id.listTimeline);

		lists = new HashMap<String, String>();
		init();
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs
				.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
					public void onSharedPreferenceChanged(
							SharedPreferences arg0, String arg1) {
						new TwitterClient(getApplicationContext())
								.setProxySettings();
						requery = true;
					}
				});
	}

	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {

		final String selectedText = (String) parent.getItemAtPosition(position);
		// If nothing was selected return
		if (selectedText == "" || selectedText.equals(null))
			return;
		try {
			// Need to clear out the list before re-populating it
			m_adapter.clear();

			// Show a progress dialog because we have to go get the statuses
			// from Twitter
			m_ProgressDialog = ProgressDialog.show(ListTimeline.this,
					"Please wait...", "Retrieving statuses ...", true);

			// Spawn a new thread to go get the statuses from Twitter because
			// this may take time
			new Thread(new Runnable() {
				public void run() {
					String errorMessage = null;
					String listID = lists.get(selectedText);
					try {
						timeline = new TwitterClient(getApplicationContext())
								.getTwitter().getListStatuses(listID);
					} catch (TwitterException e) {
						errorMessage = e.getMessage();
					}
					m_ProgressDialog.dismiss();

					if (errorMessage == null)
					// Pass the results to the message handler
					// I do this because we can't make UI changes in this thread
					listStatusMessageHandler.sendMessage(Message.obtain(
							listStatusMessageHandler, 0, timeline));
					else
						listStatusMessageHandler.sendMessage(Message.obtain(
								listStatusMessageHandler, 0, errorMessage));
				}
			}).start();

		} catch (TwitterException e) {
			Log.e(TAG, "Updater.run exception: " + e);
		}
		requery = false;
	}

	private void init() {
		// Show a progress dialog because we have to go get the lists from
		// Twitter
		if (requery) {
			m_ProgressDialog = ProgressDialog.show(ListTimeline.this,
					"Please wait...", "Retrieving lists ...", true);
			m_adapterForSpinner.clear();
			// Spawn a new thread to go get the lists from Twitter because this
			// may
			// take time
			new Thread(new Runnable() {
				public void run() {
					String errorMessage = null;
					twitter = new TwitterClient(getApplicationContext())
							.getTwitter();
					if (twitter != null) {
						try {
							lists = twitter.getLists();
						} catch (TwitterException e) {
							errorMessage = e.getMessage();
						}
					} else
						errorMessage = "Unable to connect to Twitter.  Check username, password, and proxy settings in Prefs.";
					m_ProgressDialog.dismiss();

					if (errorMessage == null)
						// Pass the results to the message handler
						// I do this because we can't make UI changes in this
						// thread
						listMessageHandler.sendMessage(Message.obtain(
								listMessageHandler, 0, lists));
					else
						listMessageHandler.sendMessage(Message.obtain(
								listMessageHandler, 0, errorMessage));

				}
			}).start();
		}
		requery = false;
	}

	@Override
	public void onResume() {
		super.onResume();
		// Start the UpdaterService
		init();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
}
